package com.crm.system.service.impl.contractManager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.crm.common.model.DhPageInfo;
import com.crm.common.util.DateUtil;
import com.crm.common.util.ExcelUtil4;
import com.crm.model.qo.contractManager.CustomerContractQO;
import com.crm.model.vo.contractReviewManager.CustomerContractExportVO;
import com.crm.model.vo.customerContractManager.CustomerContractVO;
import com.crm.system.service.contractManager.CustomerContractExportService;
import com.crm.system.service.contractManager.CustomerContractService;
import com.crm.system.service.sys.ImportExportService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yincuimei
 * @Date 2021/10/22 15:53
 */
@Service
public class CustomerContractExportServiceImpl implements CustomerContractExportService {
    @Autowired
    private CustomerContractService customerContractService;
    @Autowired
    private ImportExportService importExportService;

    /**
     * (客服部)合同列表--导出
     * @param response
     * @param customerContractQO
     * @author yincuimei
     */
    @Override
    public void exportCustomerContract(HttpServletResponse response,CustomerContractQO customerContractQO) throws Exception{
        ExcelWriter excelWriter = null;
        try{
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("合同记录"+ DateUtil.getDate("yyyy-MM-dd HH:mm:ss"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = ExcelUtil4.getHorizontalCellStyleStrategy();
            DhPageInfo<CustomerContractVO> pageInfo = customerContractService.selectCustomerContractVOList(customerContractQO,null,null,"createTm", "desc","0");
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            WriteSheet newMemberSheet = EasyExcel.writerSheet(0, "会员新单合同").head(CustomerContractExportVO.class).
                    registerWriteHandler(horizontalCellStyleStrategy).build();
            WriteSheet renewalSheet = EasyExcel.writerSheet(1, "会员续费合同").head(CustomerContractExportVO.class).
                    registerWriteHandler(horizontalCellStyleStrategy).build();
            WriteSheet noMemberSheet = EasyExcel.writerSheet(2, "非会员合同").head(CustomerContractExportVO.class).
                    registerWriteHandler(horizontalCellStyleStrategy).build();
            if(pageInfo != null){
                //会员新单合同&会员单次导出集合
                List<CustomerContractExportVO> newMemberContractExportList = new ArrayList<CustomerContractExportVO>();
                //会员续费集合导出集合
                List<CustomerContractExportVO> renewalContractExportList = new ArrayList<CustomerContractExportVO>();
                //非会员合同、单品合同导出集合
                List<CustomerContractExportVO> noMemberContractExportList = new ArrayList<CustomerContractExportVO>();
                List<CustomerContractVO> customerContractVOList =  pageInfo.getList();
                //导出数量
                int exportNum = 0;
                if(customerContractVOList != null && customerContractVOList.size() > 0){
                    List<CustomerContractVO> newMemberContractList = customerContractVOList.stream().filter(contract ->
                            "会员新单合同".equals(contract.getContractType())
                                    || "会员单次".equals(contract.getContractType())).collect(Collectors.toList());
                    List<CustomerContractVO> renewalContractList = customerContractVOList.stream().filter(contract ->
                            "会员续费合同".equals(contract.getContractType())).collect(Collectors.toList());
                    List<CustomerContractVO> noMemberContractList = customerContractVOList.stream().filter(contract ->
                            "非会员合同".equals(contract.getContractType())
                                    || "单品合同".equals(contract.getContractType())).collect(Collectors.toList());

                    if(newMemberContractList != null && newMemberContractList.size() > 0){
                        for(CustomerContractVO customerContractVO : newMemberContractList){
                            CustomerContractExportVO customerContractExportVO = new CustomerContractExportVO();
                            BeanUtils.copyProperties(customerContractVO,customerContractExportVO);
                            newMemberContractExportList.add(customerContractExportVO);
                        }
                    }
                    if(renewalContractList != null && renewalContractList.size() > 0){
                        for(CustomerContractVO customerContractVO : renewalContractList){
                            CustomerContractExportVO customerContractExportVO = new CustomerContractExportVO();
                            BeanUtils.copyProperties(customerContractVO,customerContractExportVO);
                            renewalContractExportList.add(customerContractExportVO);
                        }
                    }
                    if(noMemberContractList != null && noMemberContractList.size() > 0){
                        for(CustomerContractVO customerContractVO : noMemberContractList){
                            CustomerContractExportVO customerContractExportVO = new CustomerContractExportVO();
                            BeanUtils.copyProperties(customerContractVO,customerContractExportVO);
                            noMemberContractExportList.add(customerContractExportVO);
                        }
                    }
                }
                excelWriter.write(newMemberContractExportList,newMemberSheet).write(renewalContractExportList,renewalSheet).write(noMemberContractExportList,noMemberSheet);

                exportNum += newMemberContractExportList.size();
                exportNum += renewalContractExportList.size();
                exportNum += noMemberContractExportList.size();
                //插入导入/导出表
                importExportService.insertExportService(exportNum,"1","2","4");
            }
        }catch(Exception e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }finally{
            if(excelWriter != null){
                excelWriter.finish();
            }
        }
    }
}
